# -*- coding: utf-8 -*-
import os
#关闭fetchurl，让httplib直接使用socket服务来连接
os.environ['disable_fetchurl'] = "1" 
import sys   
import time #import time, gmtime, strftime, localtime
from datetime import datetime
import traceback
import httplib
import urllib 
import urllib2
# 打开urllib2的debug开关
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPSHandler(1)))

import hashlib
import json
import string
import base64
import cPickle

from bottle import *
from bottle import __version__ as bottleVer
from bottle import jinja2_template as template

import requests
import pprint as pp

from config import CFG
from xsettings import XCFG
#_k4incr = CFG.TOT
#KV = CFG.KV #sae.kvdb.KVClient()
#BK = CFG.BK

debug(True)
APP = Bottle()

#@view('404.html')
@APP.get('/log')
def log_inti():
    hislog = _list4sae()
    #return None
    return template('log'
                , VER = CFG.VERSION
                , crt_log=""
                , his_log=hislog
                )

def _list4sae(tag=CFG.TAGqp):
    r = requests.get(CFG._SRV)
    print "\n", r.url
    #pp.pprint(r.json())
    _pli = r.json()['logs']
    print _pli
    _exp = []
    for l in _pli:
        if CFG.GAP0 in l:
            ctag, msg = l.split(CFG.GAP0)
            if ctag == tag:
                _exp.append(msg)
    _exp.sort()
    print _exp
    return _exp

    _pli = KV.get(CFG.K4D['p'])
    _exp = []
    for k in _pli:
        #print l.split(CFG.GAP0)
        l = KV.get(k)
        #print l
        if l:
            if CFG.GAP0 in l:
                ctag, msg = l.split(CFG.GAP0)
                #print msg.encode('utf8')
                if ctag == tag:
                    #_exp += msg+'\n'
                    _exp.append(msg.decode('utf8'))
    #_exp.sort(reverse=True)
    _exp.sort()
    return _exp


@APP.post('/log')
def put_log():
    log = request.forms.get('log')#.decode('utf8')
    print "log<<", log
    if 0 == len(log):
        print "EMPTY msg."
    else:
        print log
        _ps1 = CFG.TAGqp
        payload = {'log': "{}{}{}".format(_ps1
                            , CFG.GAP0
                            , log#.encode('utf8')
                            ) }
        #print payload
        if 0 == len(log):
            pass
        else:
            r = requests.put(CFG._SRV, data=payload)
            print r.text
        #return None

    hislog = _list4sae()
    return template('log'
                , VER = CFG.VERSION
                , crt_log=log.decode('utf8')
                , his_log=hislog
                )



#@view('404.html')
@APP.error(404)
def error404(error):
    return '''


\          SORRY            /
 \                         /
  \    This page does     /
   ]   not exist yet.    [    ,'|
   ]                     [   /  |
   ]___               ___[ ,'   |
   ]  ]\             /[  [ |:   |
   ]  ] \           / [  [ |:   |
   ]  ]  ]         [  [  [ |:   |
   ]  ]  ]__     __[  [  [ |:   |
   ]  ]  ] ]\ _ /[ [  [  [ |:   |
   ]  ]  ] ] (#) [ [  [  [ :===='
   ]  ]  ]_].nHn.[_[  [  [
   ]  ]  ]  HHHHH. [  [  [
   ]  ] /   `HH("N  \ [  [
   ]__]/     HHH  "  \[__[
   ]         NNN         [
   ]         N/"         [
   ]         N H         [
  /          N            \

/                           \

roaring zoomquiet+404@gmail.com
'''
#    return template('404.html')

@APP.route('/favicon.ico')
def favicon():
    abort(204)
    
@APP.route('/static/<filename>')
def server_static(filename):
    return static_file(filename, root='static')
    






